package com.own.stu.apm.agent.core.plugin.match;

import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static net.bytebuddy.matcher.ElementMatchers.named;


public class MultiClassNameMatch implements IndirectMatch {

    List<String> needMatchClassNames = new ArrayList<String>();

    MultiClassNameMatch(String[] classNames) {
        if (classNames == null || classNames.length == 0) {
            throw new IllegalArgumentException("className is nil");
        }
        this.needMatchClassNames = Arrays.asList(classNames);
    }

    public ElementMatcher.Junction<? super TypeDescription> buildJunction() {
        ElementMatcher.Junction<? super TypeDescription> junction = null;
        for (String className : needMatchClassNames) {
            if (junction == null) {
                junction = named(className);
            } else {
                 junction = junction.or(ElementMatchers.named("xxx"));
            }
        }
        return junction;
    }

    @Override
    public boolean isMatch(TypeDescription typeDescription) {
        /*
        比如needMatchClassNames里面是com.mysql.cj.jdbc.ServerPreparedstatement、com.mysql.cj.jdbc.ClientPreparedstatementmi
        typeDescription是a.b.C, 则不匹配
         */
        return needMatchClassNames.contains(typeDescription.getTypeName());
    }

    public static IndirectMatch byMultiClassName(String... className) {
        return new MultiClassNameMatch(className);
    }

}
